import { readCookie } from './useCookie.js';

/** Web框架存到Cookie中的主题色 */
const FRAME_THEME_COLOR_KEY = 'Frame_ThemeColor';

/** 默认主题色 */
const DEFAULT_THEME_COLOR = {
  Color: "rgba(0,167,203,1.00)",
  ColorHover: "rgba(0,167,203,0.8)",
  ColorBackground: "#e6f6fa",
  ColorFocus: "#01819c",
};

/**
 * @summary 获取Cookie中保存的自定义主题
 * @description 请在组件挂载后的时点调用
 */
export const useThemeColors = () => {
  const cookieTheme = readCookie(FRAME_THEME_COLOR_KEY);
  if (
    cookieTheme === undefined ||
    cookieTheme === 'undefined' ||
    !cookieTheme
  ) {
    // cookie中取不到自定义主题色设置时，不处理，用默认
    return DEFAULT_THEME_COLOR;
  }
  const themeColors = JSON.parse(cookieTheme);
  document.body.style.setProperty('--theme-color', themeColors.Color);
  document.body.style.setProperty(
    '--theme-color-hover',
    themeColors.ColorHover
  );
  document.body.style.setProperty(
    '--theme-color-background',
    themeColors.ColorBackground
  );
  document.body.style.setProperty(
    '--theme-color-focus',
    themeColors.ColorFocus
  );
  return themeColors;
};


/** Web框架中切换系统主题 */
export const onThemeChange = (e) => {
  if (e.data.type == 'USER_SKIN_CHANGE') {
    console.log('USER_SKIN_CHANGE', e.data.ThemeColor);
    if (e.data.ThemeColor) {
      const { Color, ColorHover, ColorBackground, ColorFocus } =
        e.data.ThemeColor;
      document.body.style.setProperty('--theme-color', Color);
      document.body.style.setProperty('--theme-color-hover', ColorHover);
      document.body.style.setProperty(
        '--theme-color-background',
        ColorBackground
      );
      document.body.style.setProperty('--theme-color-focus', ColorFocus);
    }
  }
};

export default {
  useThemeColors,
  onThemeChange,
};
